#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

typedef struct {
    char *msg;
    int len;
}Result;

void *red_thread(void *arg)
{
    //得到传入的code值
    char code = *((char *)arg);

    char input_buf[10];
    while(1)
    {
        //读取输入
        read(STDIN_FILENO, input_buf, sizeof(input_buf));
        if(input_buf[0] == code)
        {
            printf("红玫瑰离开了 \n");
            Result *result = (Result *)malloc(sizeof(Result));
            result->msg = "红玫瑰独自去了哈尔滨";
            result->len = strlen(result->msg);
            return result;
        }
        else
        {
            printf("红玫瑰接收到消息:%s\n",input_buf);
        }
    }
}

void *white_thread(void *arg)
{
    //得到传入的code值
    char code = *((char *)arg);

    char input_buf[10];
    while(1)
    {
        //读取输入
        read(STDIN_FILENO, input_buf, sizeof(input_buf));
        if(input_buf[0] == code)
        {
            printf("白玫瑰离开了 \n");
            Result *result = (Result *)malloc(sizeof(Result));
            result->msg = "白玫瑰独自去了海南";
            result->len = strlen(result->msg);
            return result;
        }
        else
        {
            printf("白玫瑰接收到消息:%s\n",input_buf);
        }
    }
}


int main(int argc, char *argv[]) 
{
    //创建两个线程
    pthread_t red_pt , white_pt;
    char red_code = 'r';
    char white_code = 'w';
    pthread_create(&red_pt, NULL, red_thread, &red_code);
    pthread_create(&white_pt, NULL, white_thread, &white_code);

    //等待分线程结束
    Result *red_result;
    Result *white_result;

    pthread_join(red_pt, (void **)&red_result);
    pthread_join(white_pt, (void **)&white_result);

    printf("main线程得到红玫瑰结局:%s, len =%d\n",red_result->msg, red_result->len);
    printf("main线程得到白玫瑰结局:%s, len =%d\n",white_result->msg, white_result->len);
    return 0;

}



